package biz

import (
	itempb "gitee.com/shuokeyun/apis/item-service/api/v1"
	merchantpb "gitee.com/shuokeyun/apis/merchant-service/api/v1"
	orderpb "gitee.com/shuokeyun/apis/order-service/api/v1"
	"gitee.com/shuokeyun/med-bff/internal/domain"
)

func doConvCreateOrderRequest(do *domain.CreateOrder, merchant *merchantpb.GetMerchantReply, items []*itempb.GetItemReply) *orderpb.CreateOrderRequest {
	if do == nil {
		return nil
	}
	var ext *orderpb.OrderExt
	if do.Ext != nil {
		ext = &orderpb.OrderExt{
			Remark:            do.Ext.Remark,
			Department:        do.Ext.Department,
			OutpatientNo:      do.Ext.OutpatientNo,
			BedNo:             do.Ext.BedNo,
			ClinicalDiagnosis: do.Ext.ClinicalDiagnosis,
		}
	}
	itemMap := make(map[string]*itempb.GetItemReply)
	for _, item := range items {
		itemMap[item.Code] = item
	}
	barcodes := make([]*orderpb.OrderBarcodeCreate, len(do.Barcodes))
	for k, barcode := range do.Barcodes {
		itemList := make([]*orderpb.OrderItemCreate, len(barcode.ItemCodes))
		for key, itemCode := range barcode.ItemCodes {
			itemList[key] = &orderpb.OrderItemCreate{
				ItemCode:    itemCode,
				ItemName:    itemMap[itemCode].Name,
				Price:       100,
				MarketPrice: itemMap[itemCode].MarketPrice,
			}
		}
		barcodes[k] = &orderpb.OrderBarcodeCreate{
			Barcode:      barcode.Barcode,
			SamplingTime: barcode.SamplingTime,
			Consumable:   barcode.Consumable,
			Number:       barcode.Number,
			Status:       orderpb.BarcodeStatus_WAITING_RECEIVE,
			Items:        itemList,
		}
	}
	var originals []*orderpb.OrderOriginalCreate
	for _, itemCode := range do.OriginalItemCodes {
		originals = append(originals, &orderpb.OrderOriginalCreate{
			ItemCode:       itemCode,
			ItemName:       itemMap[itemCode].Name,
			ItemCodeDetail: itemMap[itemCode].ChildItem,
			Price:          100,
			MarketPrice:    itemMap[itemCode].MarketPrice,
		})
	}
	users := make([]*orderpb.OrderUserCreate, len(do.Users))
	for k, user := range do.Users {
		users[k] = &orderpb.OrderUserCreate{
			UserId:   user.UserId,
			Name:     user.Name,
			Age:      user.Age,
			Sex:      user.Sex,
			Mobile:   user.Mobile,
			CardType: orderpb.UserCardType(user.CardType),
			CardId:   user.CardId,
		}
	}
	request := &orderpb.CreateOrderRequest{
		AppId:          do.AppId,
		Status:         orderpb.OrderStatus_WAITING_PAYMENT,
		SettleType:     orderpb.OrderSettleType(merchant.SettleType),
		PriceArea:      merchant.PriceArea,
		Brand:          do.Brand,
		TotalPrice:     100,
		OrderPrice:     200,
		MerchantId:     do.MerchantId,
		MerchantUserId: do.MerchantUserId,
		SalesmanId:     merchant.SalesmanId,
		Ext:            ext,
		Barcodes:       barcodes,
		Originals:      originals,
		Users:          users,
	}
	return request
}
